from api.models.config import Config
from api.utils.response import success_response, error_response
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import json

# 获取所有配置
@csrf_exempt
def get_config_list(request):
    """
    获取所有配置信息
    """
    try:
        configs = Config.objects.all()
        config_list = [{"key": config.key, "value": config.value , "description": config.description} for config in configs]
        return success_response(data=config_list, message='获取配置列表成功')
    except Exception as e:
        return error_response(message=f'获取配置列表失败: {str(e)}')

# 批量保存配置
@csrf_exempt
def save_configs(request):
    """
    批量保存配置信息
    请求体格式：
    {
        "configs": [
            {"key": "free_user_limit", "value": "1000"},
            {"key": "max_text_length", "value": "5000"}
        ]
    }
    """
    try:
        if request.method != 'POST':
            return error_response(message='请求方法错误')
            
        data = json.loads(request.body)
        configs = data.get('configs', [])
        
        if not isinstance(configs, list):
            return error_response(message='配置数据格式错误')
            
        # 批量更新或创建配置
        for config_item in configs:
            key = config_item.get('key')
            value = config_item.get('value')
            
            if not key or value is None:
                continue
                
            Config.objects.update_or_create(
                key=key,
                defaults={'value': value}
            )
            
        return success_response(message='保存配置成功')
    except json.JSONDecodeError:
        return error_response(message='请求数据格式错误')
    except Exception as e:
        return error_response(message=f'保存配置失败: {str(e)}')

# 删除配置
@csrf_exempt
def delete_config(request, key):
    """
    删除指定配置
    """
    try:
        config = Config.objects.filter(key=key).first()
        if config:
            config.delete()
            return success_response(message='删除配置成功')
        return error_response(message='配置不存在')
    except Exception as e:
        return error_response(message=f'删除配置失败: {str(e)}')
